package com.qijia.common.security;

import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.springframework.context.ApplicationContext;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.taglibs.authz.AuthorizeTag;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class AuthorizeResourceTag extends AuthorizeTag {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4588129485378309733L;
	private String				doAction			= null;	
	private String				resourceString;

	// TODO here
	public int doStartTag() throws JspException {
	    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		if (null == resourceString || "".equals(resourceString)) {
		    String uri = (String)request.getAttribute("javax.servlet.forward.request_uri");
	        if (uri == null)
	        {
	            uri = ((HttpServletRequest) pageContext.getRequest()).getRequestURI();
	        }
		    resourceString = uri;
		}
		ServletContext context = pageContext.getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		String contextPath = request.getContextPath();
		if (resourceString.indexOf(contextPath) != -1) {
		    resourceString = resourceString.replace(contextPath, "");
		}
		//System.out.print(resourceString);
		//注释原来URL资源权限标签
//		if (doAction != null)
//		{
//		    //UrlFilterInvocationDefinitionMap ump = (UrlFilterInvocationDefinitionMap) source.getFilterInvocationDefinitionSource();
//		    //String resource = ump.lookupResource(resourceString);
//		    if (logger.isDebugEnabled())
//		    {
//		    //    logger.debug("### AuthorizeResourceTag input:"+resourceString +" Action:"+doAction +" match:"+ resource);
//		    }
//		}
//		
		Collection<ConfigAttribute> cad = null;
//		if(!ConfigUtil.getInstance().getIsStoreFront()){
		InvocationSecurityMetadataSourceService source = (InvocationSecurityMetadataSourceService) ctx.getBean("mySecurityMetadataSource");
		cad = source.getConfigAttributesByKey(resourceString);
//		}else{
//			FilterSecurityInterceptor source = (FilterSecurityInterceptor) ctx.getBean("filterInvocationInterceptor");
//			//spring-security.xml配置PATTERN_TYPE_APACHE_ANT时对应PathBasedFilterInvocationDefinitionMap
//			PathBasedFilterInvocationDefinitionMap fi = (PathBasedFilterInvocationDefinitionMap)source.getObjectDefinitionSource();
//			cad = fi.lookupAttributes(resourceString);
//		}
		if (cad != null) {
			//System.out.println(resourceString+"---"+getRoleNames(cad));
			this.setIfAnyGranted(getRoleNames(cad));
			return super.doStartTag();
		}
		// if not found these resource .then include.
		return EVAL_BODY_INCLUDE;
	}
	
	private String getRoleNames(Collection<ConfigAttribute> cads)
	{
	    StringBuffer roleNameSb = new StringBuffer();
        int count = 0;
        for(ConfigAttribute config : cads){
        	if (count == 0) {
                roleNameSb.append(config.getAttribute());
            } else {
                roleNameSb.append("," + config.getAttribute());
            }
            count++;
        }
        return roleNameSb.toString();
	}

	public String getDoAction() {
		return doAction;
	}

	public String getResourceString() {
		return resourceString;
	}

	public void setDoAction(String doAction) {
		this.doAction = doAction;
	}

	public void setResourceString(String resourceString) {
		this.resourceString = resourceString;
	}
}
